package com.jacky.ws.server;

import com.jacky.ws.handler.WebSocketTextFrameHandler;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.stream.ChunkedWriteHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression;
import org.springframework.stereotype.Component;

@Component
@ConditionalOnExpression("'${webSocket.run}'.equals('simple')")
public class SimpleWebsocketServer implements CommandLineRunner {

    private final Logger LOG = LoggerFactory.getLogger(SimpleWebsocketServer.class);

    @Value("${webSocket.simple.port:8070}")
    private Integer serverPort;
    @Value("${webSocket.simple.websocket-path:ws://127.0.0.1:8070/simple-ws}")
    private String webSocketPath;

    public void startServer() {
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workGroup = new NioEventLoopGroup();
        try {
            ServerBootstrap bootstrap = new ServerBootstrap();
            bootstrap.group(bossGroup, workGroup).channel(NioServerSocketChannel.class)
                    .handler(new LoggingHandler(LogLevel.INFO)) // 在bossGroup中添加一个日志处理器
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ChannelPipeline pipeline = ch.pipeline();
                            // 基于http协议的长连接, 需要使用http协议的编码 解码器
                            pipeline.addLast(new HttpServerCodec());
                            // 以块的方式处理
                            pipeline.addLast(new ChunkedWriteHandler());
                            // http 数据传输过程中是分段的, HttpObjectAggregator将多个段聚合起来
                            // 当浏览器发起大量数据的时候, 会发起多次http请求
                            pipeline.addLast(new HttpObjectAggregator(65535));
                            // 对于websocket 是以frame的形式传递WebSocketFrame
                            // WebSocketServerProtocolHandler 会将http协议升级为ws协议,即保持长链接
                            pipeline.addLast(new WebSocketServerProtocolHandler(webSocketPath));
                            // 自定义handler专门处理浏览器请求
                            pipeline.addLast(new WebSocketTextFrameHandler());
                        }
                    });
            ChannelFuture future = bootstrap.bind(serverPort).sync();
            future.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            LOG.error("simple webSocket start cause error:", e);
        } finally {
            bossGroup.shutdownGracefully();
            workGroup.shutdownGracefully();
        }
    }

    @Override
    public void run(String... args) throws Exception {
        LOG.info("simple webSocket server port:{}", serverPort);
        this.startServer();
    }
}
